package it.uniroma3.dia.ia.textcategorization.model;

import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

/**
 * 
 * This class represents categories.
 * 
 * @author Marco Liceti
 *
 */
public final class Category {
	
	private final List<String> steps;
	
	/**
	 * Creates a new Category instance from a sequence
	 * of steps into a directory (or, more precisely, a taxonomy).
	 * 
	 * @param steps A List of String objects, each representing a step.
	 * 
	 */
	public Category(List<String> steps) {
		this.steps = new LinkedList<String>(steps);
	}
	
	/**
	 * 
	 * Returns a sequence of steps into a directory
	 * (or, more precisely, a taxonomy),
	 * corresponding to this Category instance.
	 * 
	 * @return the List of String objects representing the steps
	 * 
	 */
	public List<String> getSteps() {
		return new LinkedList<String>(this.steps);
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		} else if (obj instanceof Category) {
			Category other = (Category) obj;
			String otherString = other.toString();
			return this.toString().equals(otherString);
		}
		return false;
	}

	@Override
	public int hashCode() {
		return this.toString().hashCode();
	}

	@Override
	public String toString() {
		return this.asPath();
	}

	/**
	 * 
	 * Returns a newly created Category instance from
	 * a String representation.
	 * 
	 * @param representation The String representation
	 * @return the corresponding Category instance.
	 * 
	 */
	public static Category valueOf(String representation) {
		List<String> steps = new LinkedList<String>();
		
		Scanner scanner = new Scanner(representation);
		scanner.useDelimiter("/");
		while (scanner.hasNext()) {
			steps.add(scanner.next());
		}
		
		return new Category(steps);
	}

	/**
	 * 
	 * Return a path-like String representation
	 * of this Category.
	 * 
	 * @return a path-like String representation
	 */
	public String asPath() {
		StringBuilder sb = new StringBuilder();
		for (String step : this.steps) {
			sb.append(step);
			sb.append("/");
		}
		sb.delete(sb.length() - 1, sb.length());
		return sb.toString();
	}
	
}
